#ifndef LOG_HPP
#define LOG_HPP

#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
#include "Mutex.hpp"
#include <unistd.h>
#include <sstream>

namespace LogModule
{
    using namespace MutexModule;
    const std::string gsep = "\n\r";
    class LogStrategy
    {
    public:
        ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    // 显示器打印子类的策略
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        void SyncLog(const std::string &message) override
        {
            LockGuard lock(_mutex);
            std::cout << message << gsep;
        }
        ~ConsoleLogStrategy() = default;

    private:
        Mutex _mutex;
    };

    const std::string defaultpath = "./log";
    const std::string defaultfile = "log.log";

    // 文件打印子类的策略
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &file = defaultfile)
            : _path(path), _file(file)
        {
            if (std::filesystem::exists(_path))
                return;

            try
            {
                std::filesystem::create_directory(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << "Error: " << e.what() << std::endl;
            }
        }

        void SyncLog(const std::string &message) override
        {
            LockGuard lock(_mutex);
            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _file;
            std::ofstream ofs(filename, std::ios::app);
            if (!ofs.is_open())
            {
                std::cerr << "Error: open file " << filename << " failed." << std::endl;
                return;
            }

            ofs << message << gsep;
            ofs.close();
        }

    private:
        std::string _path;
        std::string _file;
        Mutex _mutex;
    };

    // 形成一天完整的日志&&根据上面的策略，选择不用的刷新方式

    // 1. 形成日志等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string Level2Str(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    std::string GetTimeStamp()
    {
        time_t now = time(nullptr);
        struct tm *tm_now = localtime(&now);
        char buffer[80];
        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_now);
        return std::string(buffer);
    }

    // 2. 日志类
    // 用来选择刷新策略，并提供日志输出接口
    class Logger
    {
    public:
        Logger()
        {
            EnableConsoleLogStrategy();
        }

        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }

        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }
        // 日志输出接口
        class LogMessage
        {
        public:
            LogMessage(LogLevel &level, const std::string &src_name, int line_number, Logger &logger)
                : _curr_time(GetTimeStamp()),
                  _level(level), _pid(getpid()),
                  _src_name(src_name),
                  _line_number(line_number),
                  _logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _curr_time << "]["
                   << Level2Str(_level) << "]["
                   << _pid << "]["
                   << _src_name << ":"
                   << _line_number << "] "
                   << "- ";
                _loginfo = ss.str();
            }

            // 重载 << 运算符，用于输出日志信息
            template <typename T>
            LogMessage &operator<<(const T &msg)
            {
                std::stringstream ss;
                ss << msg;
                _loginfo += ss.str();
                return *this;
            }

            // 析构函数，用于刷新日志信息
            ~LogMessage()
            {
                if (_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_loginfo);
                }
            }

        private:
            std::string _curr_time;
            LogLevel _level;
            pid_t _pid;
            std::string _src_name;
            int _line_number;
            std::string _loginfo;
            Logger &_logger;
        };

        LogMessage operator()(LogLevel level, const std::string &src_name, int line_number)
        {
            return LogMessage(level, src_name, line_number, *this);
        }

        ~Logger() = default;

    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    Logger log;

    // 使用宏，简化用户操作，获取文件名和行号
    #define LOG(level) log(level, __FILE__, __LINE__)
    #define Enable_Console_Log_Strategy() log.EnableConsoleLogStrategy()
    #define Enable_File_Log_Strategy() log.EnableFileLogStrategy()
}

#endif